﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace VirtualTournaments.Business.Tournaments
{
	public class Standings : IEnumerable<TeamStatics>
	{
		private List<TeamStatics> _teamsList;
		private Dictionary<String, TeamStatics> _teamsMap;

		public Standings(IEnumerable<Team> teams)
		{
			if (teams != null)
			{
				TeamsList = new List<TeamStatics>();
				TeamsMap = new Dictionary<String, TeamStatics>();
				foreach (Team team in teams)
				{
					TeamStatics teamStatics = new TeamStatics(team);
					TeamsList.Add(teamStatics);
					TeamsMap.Add(team.Name, teamStatics);
				}
			}
		}

		protected virtual List<TeamStatics> TeamsList
		{
			get { return _teamsList; }
			set { _teamsList = value; }
		}

		protected virtual Dictionary<String, TeamStatics> TeamsMap
		{
			get { return _teamsMap; }
			set { _teamsMap = value; }
		}

		public void Update(IEnumerable<MatchResult> results)
		{
			foreach (MatchResult result in results)
			{
				TeamsMap[result.Local.Name].RegisterMatch(result.LocalGoals, result.VisitorGoals);
				TeamsMap[result.Visitor.Name].RegisterMatch(result.VisitorGoals, result.LocalGoals);
			}
			TeamsList.Sort();
		}

		public IEnumerable<TeamStatics> GetTeamsStatics(int position)
		{
			TeamStatics oneTeam = TeamsList[position - 1];
			List<TeamStatics> teamsInPosition = new List<TeamStatics>();
			teamsInPosition.Add(oneTeam);
			for (int i = position - 2; (i >= 0) && (oneTeam.CompareTo(TeamsList[i]) == 0); --i)
				teamsInPosition.Add(TeamsList[i]);
			for (int i = position; (i < TeamsList.Count) && (oneTeam.CompareTo(TeamsList[i]) == 0); ++i)
				teamsInPosition.Add(TeamsList[i]);
			return teamsInPosition;
		}

		public TeamStatics GetTeamStatics(String teamName)
		{
			return TeamsMap[teamName];
		}

		public IEnumerator<TeamStatics> GetEnumerator()
		{
			return TeamsList.GetEnumerator();
		}

		IEnumerator IEnumerable.GetEnumerator()
		{
			return TeamsList.GetEnumerator();
		}
	}
}
